package com.demo.travel.db;

import android.content.Context;

import com.demo.travel.bean.UserBean;
import com.j256.ormlite.dao.Dao;

import java.sql.SQLException;
import java.util.List;

/**
 * Create author
 * 用户数据库管理类
 */

public class UserDao {

    private Context context;

    private Dao<UserBean, Integer> dao;

    /*
     * 构造dao对象
     * */
    public UserDao(Context context) {
        this.context = context;
        try {
            this.dao = DatabaseHelper.getHelper(context).getDao(UserBean.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 检查登录是否成功
     * */
    public UserBean checkLogin(String username,String password){
        List<UserBean> users = null;
        try {
            users=dao.queryBuilder().where()
                    .eq("username", username).and()
                    .eq("password", password).query();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (users == null || users.isEmpty()) {
            return null;
        }
        return users.get(0);
    }

    /**
     * 检查用户是否存在
     * */
    public boolean userExist(String username){
        List<UserBean> users = null;
        try {
            users=dao.queryBuilder().where()
                    .eq("username", username).query();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (users == null || users.isEmpty()) {
            return false;
        }
        return true;
    }

    /*
     *
     *
     * 插入数据
     * */
    public int insert(UserBean entity){
        int result = 0;
        try {
            result = dao.create(entity);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }


    /*
     *
     * 获取所有数据
     * */
    public List<UserBean> getAll(){
        List<UserBean> noteInfos = null;
        try {
            noteInfos = dao.queryForAll();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return noteInfos;
    }



}